//
//  ViewController.swift
//  CitySearch
//
//  Created by guotonglin on 2020/6/1.
//  Copyright © 2020 guotonglin. All rights reserved.
//

import UIKit
import RxDataSources
import RxSwift

class SearchCityViewController: UIViewController, Storyboardable {

    @IBOutlet weak var roundedView: UIView!
    @IBOutlet weak var searchTextField: UITextField!
    @IBOutlet weak var tableView: UITableView!
    
    private var viewModel: SearchCitiViewPresentable!
    var viewModelBuilder: SearchCitiViewPresentable.ViewModelBuilder!
    private static let cellId = "cityCellId"
    
    private let bag = DisposeBag()
    
    // 使用 RxDataSource 驱动 tableview
    private lazy var datasource = RxTableViewSectionedReloadDataSource<CityItemsSection>(configureCell: { _, tableView, indexPath, item in
        let cityCell = tableView.dequeueReusableCell(withIdentifier: SearchCityViewController.cellId, for: indexPath) as! CityCell
        cityCell.configure(usingViewModel: item)
        return cityCell
    })
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // ViewModelBuilder 创建出 ViewModel
        self.viewModel = viewModelBuilder((
            searchText: searchTextField.rx.text.orEmpty.asDriver(),
            citySelected: self.tableView.rx.modelSelected(CityViewModel.self).asDriver()
        ))
        
        self.setupUI()
        self.setupBinding()
    }
}

extension SearchCityViewController {

    func setupUI() {
        self.title = "Airports"
        tableView.tableFooterView = UIView.init()
        tableView.register(UINib.init(nibName: "CityCell", bundle: nil), forCellReuseIdentifier: SearchCityViewController.cellId)
    }

    func setupBinding() {
        // Output 是从 ViewModel 的输出信号
        // 从ViewModel 输出的  cityes: Driver<[CityItemsSection]> 信号 可以直接用于 self.datasource 并带动 tableview
        self.viewModel.output.cityes
            .drive(self.tableView.rx.items(dataSource: self.datasource))
            .disposed(by: bag)
    }
}
